package com.qbw.app.module.home.fragment;

import androidx.databinding.BindingAdapter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.http.okhttp.HttpTask;
import com.lib.util.ResUtil;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.databinding.HomeNewFragmentBinding;
import com.qbw.app.manager.LocationManager;
import com.qbw.app.model.Location;
import com.qbw.app.model.TravelGps;
import com.qbw.app.model.Vehicle;
import com.qbw.app.module.common.fragment.CommonFragment;
import com.qbw.app.module.common.util.Gps;
import com.qbw.app.module.common.util.PositionUtil;
import com.qbw.app.module.vehicle.VehicleDataBindingAdapter;
import com.qbw.core.observable.ObservableInt;
import com.qbw.l.L;
import com.qbw.spm.P;

import java.util.ArrayList;
import java.util.List;

import static com.qbw.app.Constant.KEY_MAP;
import static com.qbw.app.Constant.KEY_VEHICLE;
import static com.qbw.app.Constant.MAP_BAIDU;
import static com.qbw.app.Constant.MAP_DEFAULT;
import static com.qbw.app.Constant.MAP_GOOGLE;
import static com.qbw.app.Constant.VEHICLE_STATUS_DRIVING;
import static com.qbw.app.Constant.VEHICLE_STATUS_FLAMEOUT;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_LOCATION;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_VEHICLE_LIST;

/**
 * 车辆位置
 *
 * @author QBW
 * @date 2019/8/27
 */
public class NewHomeFragment extends CommonFragment<HomeNewFragmentBinding> implements OnMapReadyCallback, View.OnClickListener, View.OnLongClickListener {

    private final int COUNT_LOOP = 5;
    private Handler mHandler = new Handler();
    private GoogleMap mGoogleMap;
    private float mBaiduInitScale = 15F;
    private float mGoogleInitScale = 15F;
    private ObservableInt mSecond = new ObservableInt(-1);
    private int mCount = COUNT_LOOP;
    private android.location.Location mCurrentLocation;
    private Overlay mBaiduMarker;
    private Marker mGoogleMarker;
    private static final String KEY_GPS_DATA = NewHomeFragment.class.getName() + "_key_gps_data";


    public static NewHomeFragment createInstance() {
        NewHomeFragment ins = new NewHomeFragment();
        return ins;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.home_new_fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mBinding.setSecond(mSecond);
        initMap();
//        getVehicleList();
//        mBinding.ivRefresh.setOnClickListener(this);
//        mBinding.ivAdd.setOnClickListener(this);
//        mBinding.ivMinus.setOnClickListener(this);

    }

    private void setLocationView(Location location){
        mBinding.setLocation(location);
        if (location.getDrivingState() == VEHICLE_STATUS_DRIVING) {
            mHandler.post(mCountTimeRunn);
        }
        if (location.getDrivingState() == Constant.VEHICLE_STATUS_INVALID) {
            location.setAddress(ResUtil.getString(R.string.no_gps_data));
        } else {
            if (TextUtils.isEmpty(location.getAddress())) {
                location.setAddress(ResUtil.getString(R.string.no_gps_data));
            }
        }
    }

    private Runnable mGetCurrentLocationRunn = new Runnable() {
        @Override
        public void run() {
            mCurrentLocation = LocationManager.getInstance().getLastLocation();
            updateUi();
        }
    };

    private Runnable mCountTimeRunn = new Runnable() {
        @Override
        public void run() {
            mSecond.setValue(mCount);
            if (mCount <= 0) {
                mSecond.setValue(-1);
                mGeneralManager.getRequestManager()
                        .getVehicleRequest()
                        .getVehicleLocation(mBinding.getLocation().getVehicleCode(),
                                NewHomeFragment.this)
                        .execute();
                return;
            }
            mCount -= 1;
            mHandler.postDelayed(mCountTimeRunn, 1000);
        }
    };

    private void afterInitMap() {
        try {
            String gpsDataJson = P.getString(KEY_GPS_DATA, "");
            if (!TextUtils.isEmpty(gpsDataJson)) {
                List<TravelGps> gps = new Gson().fromJson(gpsDataJson,
                        new TypeToken<List<TravelGps>>() {}.getType());
                if (gps != null && gps.size() > 1) {
                    showTravel(gps);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            L.GL.e(e);
        }
    }

    private void showTravel(List<TravelGps> travelGpss) {
        int gpsSize = travelGpss == null ? 0 : travelGpss.size();
        L.GL.d("gpsSize[%d]", gpsSize);
        if (gpsSize < 1) {
            L.GL.w("invalid gps data size");
            return;
        }
        String map = P.getString(KEY_MAP, MAP_DEFAULT);
        if (map.equals(MAP_BAIDU)) {
            mBinding.bmapView.getMap().clear();
            TravelGps startGps = travelGpss.get(gpsSize - 1);
            TravelGps endGps = travelGpss.get(0);
            mBinding.bmapView.getMap()
                    .addOverlay(new com.baidu.mapapi.map.MarkerOptions().icon(
                            BitmapDescriptorFactory.fromResource(R.drawable.travel_start))
                            .position(new LatLng(
                                    startGps.getLatitude(),
                                    startGps.getLongitude())))
                    .setZIndex(4);
            /*mBinding.bmapView.getMap()
                             .addOverlay(new com.baidu.mapapi.map.MarkerOptions().icon(
                                     BitmapDescriptorFactory.fromResource(R.drawable.travel_end))
                                                                                 .position(new LatLng(
                                                                                         endGps.getLatitude(),
                                                                                         endGps.getLongitude())))
                             .setZIndex(5);*/

            TravelGps travelGps;
            List<LatLng> latLngs = new ArrayList<>();
            //int seekProgress = gpsSize - mTravelProgress;
            for (int i = gpsSize - 1; i >= 0; i--) {
                travelGps = travelGpss.get(i);
                //经纬度都是0的舍弃
                if (travelGps.getLatitude() == 0f && travelGps.getLongitude() == 0f) {
                    continue;
                }
                //if (i >= seekProgress) {
                latLngs.add(new LatLng(travelGps.getLatitude(), travelGps.getLongitude()));
                //}
            }

            com.baidu.mapapi.model.LatLngBounds.Builder builder = new com.baidu.mapapi.model.LatLngBounds.Builder();
            builder.include(new LatLng(startGps.getLatitude(), startGps.getLongitude()));
            builder.include(new LatLng(endGps.getLatitude(), endGps.getLongitude()));

            L.GL.e("here1，latLngs[%d],gpsSize[%d]", latLngs.size(), gpsSize);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    L.GL.e("her3");
                    //if (!mUpdateByManual) {
//                    mBinding.bmapView.getMap()
//                                     .animateMapStatus(MapStatusUpdateFactory.newLatLngBounds(
//                                             builder.build(),
//                                             mBinding.bmapView.getWidth() - 100/*ScreenUtil.dp2px(
//                                                     VehicleLocationActivity.this,
//                                                     300)*/,
//                                             mBinding.bmapView.getHeight() - ScreenUtil.dp2px(
//                                                     VehicleLocationActivity.this,
//                                                     300)));
                    //}
                    L.GL.d("latLngs[%d]", latLngs.size());
                    if (latLngs.size() >= 2) {
                        OverlayOptions ooPolyline = new PolylineOptions().width(Constant.TRAVEL_LINE_WIDTH)
                                .color(ResUtil.getColor(
                                        R.color.travel_line_color))
                                .points(latLngs);
                        mBinding.bmapView.getMap().addOverlay(ooPolyline);
                    }
                }
            }, 500);
        } else if (map.equals(MAP_GOOGLE)) {
            if (mGoogleMap == null) {
                //mNeedShowTravel = true;
                return;
            }
            mGoogleMap.clear();
            TravelGps startGps = travelGpss.get(gpsSize - 1);
            TravelGps endGps = travelGpss.get(0);
            mGoogleMap.addMarker(new MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                    .fromResource(
                            R.drawable.travel_start))
                    .position(
                            new com.google.android.gms.maps.model.LatLng(
                                    startGps.getLatitude(),
                                    startGps.getLongitude())))
                    .setZIndex(4);
            /*mGoogleMap.addMarker(new com.google.android.gms.maps.model.MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                                                                                                    .fromResource(
                                                                                                            R.drawable.travel_end))
                                                                                      .position(
                                                                                              new com.google.android.gms.maps.model.LatLng(
                                                                                                      endGps.getLatitude(),
                                                                                                      endGps.getLongitude())))
                      .setZIndex(5);*/

            TravelGps travelGps;
            com.google.android.gms.maps.model.PolylineOptions polylineOptions = new com.google.android.gms.maps.model.PolylineOptions();
            for (int i = gpsSize - 1; i >= 0; i--) {
                travelGps = travelGpss.get(i);
                //经纬度都是0的舍弃
                if (travelGps.getLatitude() == 0f && travelGps.getLongitude() == 0f) {
                    continue;
                }
                polylineOptions.add(new com.google.android.gms.maps.model.LatLng(travelGps.getLatitude(),
                        travelGps.getLongitude()));
            }
            polylineOptions.width(Constant.TRAVEL_LINE_WIDTH)
                    .color(ResUtil.getColor(R.color.travel_line_color));
            mGoogleMap.addPolyline(polylineOptions);

            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            builder.include(new com.google.android.gms.maps.model.LatLng(startGps.getLatitude(),
                    startGps.getLongitude()));
            builder.include(new com.google.android.gms.maps.model.LatLng(endGps.getLatitude(),
                    endGps.getLongitude()));
            //CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(builder.build(), 100);
            //mGoogleMap.moveCamera(cu);
        }
    }

    private void initMap() {
        String map = P.getString(KEY_MAP, MAP_DEFAULT);
        if (MAP_BAIDU.equals(map)) {
            initBaidu();
        } else if (MAP_GOOGLE.equals(map)) {
            initGoogle();
        }
    }

    private void initBaidu() {
        mBinding.bmapView.setVisibility(View.VISIBLE);
        mBinding.bmapView.showScaleControl(false);
        mBinding.bmapView.showZoomControls(false);

        BaiduMap map = mBinding.bmapView.getMap();
        map.setMyLocationEnabled(true);
        map.setMyLocationConfiguration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL,
                true,
                BitmapDescriptorFactory.fromResource(
                                                                           /*R.drawable
                                                                           .location_icon_route_end*/
                        0)));
        //map.setOnMapClickListener(mBadiuMapClickListener);
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        map.setMapStatus(msu);

        //mLocationClient = new LocationClient(getApplicationContext());
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(1000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        //mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明

        //mLocationClient.registerLocationListener(mBaiduLocationListener = new
        // ElecAreaAddActivity.MyBaiduLocationListener());

        //mLocationClient.start();
        //mLocationClient.requestLocation();

        afterInitMap();
        Location location = mBinding.getLocation();
        /*if (location.getDrivingState() == VEHICLE_STATUS_DRIVING) {
            baiduAnimateAndAddMarker(location.getLatitude(),
                                     location.getLongitude(),
                                     R.drawable.travel_start);
            mBaiduMarker = null;
        }*/
        mHandler.removeCallbacks(mGetCurrentLocationRunn);
        mHandler.post(mGetCurrentLocationRunn);

    }

    private int getTravelEndDrawable() {
        /*int d = R.drawable.travel_driving;
        Location location = mBinding.getLocation();
        if (location == null) {
            return d;
        }*/
        Location location = mBinding.getLocation();
        return VehicleDataBindingAdapter.getTravelLocationEndDrawable1(location == null ? -1 : location
                .getDrivingState());
    }

    private Bitmap getDirectionBitmap(Bitmap bitmap) {
        Location location = mBinding.getLocation();
        if (location == null) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        int bw = bitmap.getWidth();
        int bh = bitmap.getHeight();
        //matrix.postRotate((float) location.getDirection(), bw / 2, bh / 2);
        Bitmap bitmapNew = Bitmap.createBitmap(bitmap, 0, 0, bw, bh, matrix, true);
        //bitmap.recycle();
        return bitmapNew;
    }

    private void initGoogle() {
        mBinding.googleContainer.setVisibility(View.VISIBLE);
        com.google.android.gms.maps.SupportMapFragment mapFragment = (com.google.android.gms.maps.SupportMapFragment) getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        mGoogleMap.getUiSettings().setCompassEnabled(false);
        CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(15);
        mGoogleMap.moveCamera(cameraUpdate);
        afterInitMap();
        Location location = mBinding.getLocation();
        /*if (location.getDrivingState() == VEHICLE_STATUS_DRIVING) {
            googleAnimateAndAddMarker(location.getLatitude(),
                                      location.getLongitude(),
                                      R.drawable.travel_start);
            mGoogleMarker = null;
        }*/
        mHandler.removeCallbacks(mGetCurrentLocationRunn);
        mHandler.post(mGetCurrentLocationRunn);
    }

//    @Override
//    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
//        Location location = mBinding.getLocation();
//        outState.putSerializable(Constant.KEY_LOCATION, location);
//    }

    @BindingAdapter("vehicleLocationStatusTextColor")
    public static void setVehicleLocationStatusTextColor(TextView tv, int vehicleStatus) {
        switch (vehicleStatus) {
            case VEHICLE_STATUS_DRIVING:
                tv.setTextColor(Color.parseColor("#01BC67"));
                break;
            case VEHICLE_STATUS_FLAMEOUT:
                tv.setTextColor(Color.parseColor("#E82747"));
                break;
            /*case VEHICLE_STATUS_ILLEGAL_MOVE:
                tv.setTextColor(Color.parseColor("#E82747"));
                break;*/
            default:
                tv.setTextColor(Color.parseColor("#FEFEFF"));
                break;
        }
    }

    @BindingAdapter("vehicleLocationSpeedTextShow")
    public static void setVehicleLocationSpeedTextShow(TextView tv, int vehicleStatus) {
        tv.setVisibility(vehicleStatus == VEHICLE_STATUS_DRIVING ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onClick(View v) {
        int vid = v.getId();
        Location location = mBinding.getLocation();

    }

    @Override
    public boolean onLongClick(View v) {
        int vid = v.getId();
        return false;
    }



    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (METHOD_LOCATION.equals(method)) {
            Location.Response response = (Location.Response) entity;
            Location location = response.getData();
            location.setVehicleCode(mBinding.getLocation().getVehicleCode());
            mBinding.setLocation(location);
            showTravel(location.getGpsDatas());
            updateUi();

            if (location.getDrivingState() == VEHICLE_STATUS_DRIVING) {
                mHandler.removeCallbacks(mCountTimeRunn);
                mCount = COUNT_LOOP;
                mHandler.post(mCountTimeRunn);
            }
            closeLoadingDialog();
        }else  if (METHOD_VEHICLE_LIST.equals(method)) {
            Vehicle.Response response = (Vehicle.Response) entity;
//            int p = mAdapter.getHeaderPositionByViewType(VT_CURRENT_VEHICLE);
//            if (p == -1) {
//                mAdapter.addHeader(mAdapter.getHeaderPosition(VT_CURRENT_VEHICLE,
//                        mSortedHeaderViewTypes),
//                        new HomeCurrentVehicleHolder.Data(response.getData(), null));
//            } else {
//                HomeCurrentVehicleHolder.Data data = (HomeCurrentVehicleHolder.Data) mAdapter.getHeader(
//                        p);
//                data.setVehicleList(response.getData());
//                mAdapter.updateHeader(p, data);
//            }
            Vehicle selectedVehicle = response.getData().getIndexVehicle();
            if (selectedVehicle != null) {
                getHomeInfo(selectedVehicle);
                getVehicleLocation(selectedVehicle);
            }
        } else if (METHOD_LOCATION.equals(method)) {
            Location.Response response = (Location.Response) entity;
            Location location = response.getData();
            //location.setVehicleCode((String) httpTask.getExtraParam(KEY_VEHICLE_CODE));
            Vehicle vehicle = (Vehicle) httpTask.getExtraParam(KEY_VEHICLE);
            location.setVehicleCode(vehicle.getVehicleCode());
            location.setVehicleNick(vehicle.getVehicleNick());
            L.GL.d("vehiclenick[%s]", vehicle.getVehicleNick());

        }

    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        String method = httpTask.getMethod();
        if (METHOD_LOCATION.equals(method)) {
            closeLoadingDialog();
        }
    }

    private void updateUi() {
        Location location = mBinding.getLocation();
        if (!location.isGpsValid() || location
                .getGpsTime() <= 0) {
            mBinding.tvTime.setVisibility(View.GONE);
        } else {
            mBinding.tvTime.setVisibility(View.VISIBLE);
        }

        if (!location.isGpsValid()) {
            mBinding.tvAddress.setText(R.string.no_gps_data);
        }

        // 信号
        updateGpsSignal();
        updateGsmSignal();

        String map = P.getString(KEY_MAP, MAP_DEFAULT);
        switch (map) {
            case MAP_BAIDU:
                if (location.isGpsValid()) {
                    baiduAnimateAndAddMarker(true,
                            location.getLatitude(),
                            location.getLongitude(),
                            getTravelEndDrawable());
                } else {
                    L.GL.w("车辆位置无效，显示用户当前位置");
                    if(mCurrentLocation != null) {
                        baiduAnimateAndAddMarker(true,
                                mCurrentLocation.getLatitude(),
                                mCurrentLocation.getLongitude(),
                                0);
                    } else {
                        Gps gps = PositionUtil.gps84_to_bd09_byBaiduSdk(PositionUtil.BEIJING_LAT,
                                PositionUtil.BEIJING_LNG);
                        baiduAnimateAndAddMarker(true, gps.getWgLat(), gps.getWgLon(), 0);
                    }
                }
                break;
            case MAP_GOOGLE:
                if (location.isGpsValid()) {
                    googleAnimateAndAddMarker(location.getLatitude(),
                            location.getLongitude(),
                            getTravelEndDrawable());
                } else {
                    L.GL.w("车辆位置无效，显示用户当前位置");
                    if(mCurrentLocation != null) {
                        googleAnimateAndAddMarker(mCurrentLocation.getLatitude(),
                                mCurrentLocation.getLongitude(),
                                0);
                    } else {
                        //Gps gps = PositionUtil.gps84_To_Gcj02(PositionUtil.BEIJING_LAT,
                        //        PositionUtil.BEIJING_LNG);
                        //googleAnimateAndAddMarker(gps.getWgLat(), gps.getWgLon(), 0);
                        CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(1);
                        mGoogleMap.moveCamera(cameraUpdate);
                    }
                }
                break;
            default:
                break;
        }
    }

    private void scaleMap(boolean bigger) {
        String map = P.getString(KEY_MAP, MAP_DEFAULT);
        switch (map) {
            case MAP_BAIDU:
                mBaiduInitScale += (bigger ? .5F : -.5F);
                MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(mBaiduInitScale);
                mBinding.bmapView.getMap().setMapStatus(msu);
                break;
            case MAP_GOOGLE:
                mGoogleInitScale += (bigger ? .5F : -.5F);
                if (mGoogleMap != null) {
                    CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(mGoogleInitScale);
                    mGoogleMap.moveCamera(cameraUpdate);
                }
                break;
            default:
                break;
        }
    }

    private void baiduAnimateTo(double latitude, double longitude) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }
        Gps gps = /*PositionUtil.gps84_To_Bd09(latitude, longitude)*/new Gps(latitude, longitude);
        MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(new LatLng(gps.getWgLat(),
                gps.getWgLon()));
        // 移动到某经纬度
        mBinding.bmapView.getMap().animateMapStatus(update);
    }

    /**
     * 移动到指定位置，并添加marker
     */
    private void baiduAnimateAndAddMarker(boolean animateTo,
                                          double latitude,
                                          double longitude,
                                          int positionDrawableRes) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }
        //Gps gps = PositionUtil.gps84_To_Bd09(latitude, longitude);
        Gps gps = new Gps(latitude, longitude);
        if (animateTo) {
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(new LatLng(gps.getWgLat(),
                    gps.getWgLon()));
            // 移动到某经纬度
            mBinding.bmapView.getMap().animateMapStatus(update);
        }

        if (positionDrawableRes > 0) {
            if (mBaiduMarker != null) {
                mBaiduMarker.remove();
            }
            //添加marker
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), positionDrawableRes);
            if (positionDrawableRes != R.drawable.travel_start && positionDrawableRes != R.drawable.travel_end && positionDrawableRes != R.drawable.travel_location) {
                bitmap = getDirectionBitmap(bitmap);
            }
            mBaiduMarker = mBinding.bmapView.getMap()
                    .addOverlay(new com.baidu.mapapi.map.MarkerOptions().anchor(
                            0.5f,
                            0.5f)
                            .position(
                                    new LatLng(
                                            gps.getWgLat(),
                                            gps.getWgLon()))
                            .icon(BitmapDescriptorFactory
                                    .fromBitmap(
                                            bitmap)));
            mBaiduMarker.setZIndex(6);
        }
    }

    private void googleAnimateTo(double latitude, double longitude) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }
        Gps _gps = /*PositionUtil.gps84_To_Gcj02(latitude, longitude)*/new Gps(latitude, longitude);
        // 移动到某经纬度
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new com.google.android.gms.maps.model.LatLng(
                _gps.getWgLat(),
                _gps.getWgLon()), 11);
        mGoogleMap.moveCamera(cameraUpdate);
    }

    private void googleAnimateAndAddMarker(double latitude,
                                           double longitude,
                                           int positionDrawableRes) {
        if (latitude == 0 && longitude == 0) {
            L.GL.w("invalid location");
            return;
        }
        Gps _gps = /*PositionUtil.gps84_To_Gcj02(latitude, longitude)*/new Gps(latitude, longitude);
        // 移动到某经纬度
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new com.google.android.gms.maps.model.LatLng(
                _gps.getWgLat(),
                _gps.getWgLon()), 11);
        mGoogleMap.moveCamera(cameraUpdate);

        if (positionDrawableRes > 0) {
            if (mGoogleMarker != null) {
                mGoogleMarker.remove();
            }
            //添加marker
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), positionDrawableRes);
            if (positionDrawableRes != R.drawable.travel_start && positionDrawableRes != R.drawable.travel_end && positionDrawableRes != R.drawable.travel_location) {
                bitmap = getDirectionBitmap(bitmap);
            }
            mGoogleMarker = mGoogleMap.addMarker(new MarkerOptions().icon(com.google.android.gms.maps.model.BitmapDescriptorFactory
                    .fromBitmap(bitmap))
                    .anchor(0.5f, 0.5f)
                    .position(new com.google.android.gms.maps.model.LatLng(
                            _gps.getWgLat(),
                            _gps.getWgLon())));
            mGoogleMarker.setZIndex(6);
        }
    }

    /**
     * GPS定位
     */
    private void updateGpsSignal() {
        Location location = mBinding.getLocation();
        int count = location.getSignalSpan();
        if (count < 4) {
            count = 0;
        } else if (count >= 4 && count < 6) {
            count = 1;
        } else if (count >= 6 && count < 8) {
            count = 2;
        } else if (count >= 8 && count < 10) {
            count = 3;
        } else if (count >= 10 && count < 12) {
            count = 4;
        } else if (count >= 12) {
            count = 5;
        }
        mBinding.gpsSignal.setSignal(count, R.drawable.gps_signal_bg_gray);
    }

    /**
     * 基站定位
     */
    private void updateGsmSignal() {
        Location location = mBinding.getLocation();
        int count = location.getMcc();
        if (count < 0) {
            count = 0;
        }
        if (count > 5) {
            count = 5;
        }
        mBinding.mccSignal.setSignal(count, R.drawable.gps_signal_bg_gray);
    }


    private void getVehicleList() {
        mGeneralManager.getRequestManager().getVehicleRequest().getVehicleList(this).execute();
    }

    private void getVehicleLocation(Vehicle vehicle) {
        mGeneralManager.getRequestManager()
                .getVehicleRequest()
                .getVehicleLocation(vehicle.getVehicleCode(), this)
                .addExtraParam(KEY_VEHICLE, vehicle)
                .execute();
    }

    private void getHomeInfo(Vehicle vehicle) {
        if (vehicle != null) {
            mGeneralManager.getRequestManager()
                    .getVehicleRequest()
                    .getHomeInfoNm(vehicle.getVehicleCode(), this)
                    .addExtraParam(KEY_VEHICLE, vehicle)
                    .execute();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mHandler.removeCallbacks(mCountTimeRunn);
        mHandler.removeCallbacks(mGetCurrentLocationRunn);
    }
}
